package com.lenovo.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.lenovo.testreport.user.model.Userinfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Descpription 判断是否拥有权限
 * @Author CJF
 * @Date 2019/1/18 15:03
 **/
@Component
public class IfPermission {

    @Autowired
    private RedisTemplate<Object, Object> redisTemplate;
    private static final Logger logger = LoggerFactory.getLogger(IfPermission.class);


    boolean CheckPermission(Integer PermCode, HttpServletRequest request, HttpServletResponse response) throws IOException {

        //  String msg = request.getRemoteAddr() + "######" + request.getRequestURL() + "######";
        // logger.info(msg);
        String sessionId = "Lenovo-sessionId:" + request.getSession().getId();
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        Userinfo userinfo = (Userinfo) redisTemplate.opsForValue().get(sessionId);
        Integer levelNum = userinfo.getLevelnum();


        if (levelNum != null && PermCode.equals(levelNum & PermCode)) {
            return true;
        } else {
            if (PermCode.equals(1024)) {
                response.setContentType("application/json; charset=utf-8");
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("code", 401);
                jsonObject.put("message", "No such authority! 很抱歉，您的操作失败了，该账号并未开通该功能，请联系管理员开通，谢谢配合。");
                response.getWriter().write(jsonObject.toString());
                return false;
            }
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("code", 401);
            jsonObject.put("message", "No such authority! 很抱歉，您的操作失败了，该账号并未开通该功能，请联系管理员开通，谢谢配合。");
            response.getWriter().write(jsonObject.toString());
            return false;
        }
    }

}
